package advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class Log {

    @Pointcut("execution(* service.*ServiceImpl.*(..))")
    public void pointcutName(){}


    @Before("pointcutName()")
    public void before(JoinPoint jp){
        Object proxy=jp.getThis();
        Object target=jp.getTarget();
        String methodName=jp.getSignature().getName();
        Object[] args=jp.getArgs();
        System.out.println("=====代理"+proxy.getClass().getSimpleName()+"类，目标"+target.getClass().getSimpleName()+"类，"+methodName+"方法即将执行，参数"+ Arrays.toString(args));
    }

    @AfterReturning(value = "pointcutName()",returning = "r")
    public void afterReturning(JoinPoint jp,Object r){
        Object proxy=jp.getThis();
        Object target=jp.getTarget();
        String methodName=jp.getSignature().getName();
        Object[] args=jp.getArgs();
        System.out.println("=====代理"+proxy.getClass().getSimpleName()+"类，目标"+target.getClass().getSimpleName()+"类，"+methodName+"方法已经返回，参数"+ Arrays.toString(args)+",返回值"+r);
    }

    @AfterThrowing(value = "pointcutName()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Exception e){
        Object proxy=jp.getThis();
        Object target=jp.getTarget();
        String methodName=jp.getSignature().getName();
        Object[] args=jp.getArgs();
        System.out.println("=====代理"+proxy.getClass().getSimpleName()+"类，目标"+target.getClass().getSimpleName()+"类，"+methodName+"方法已经出错，参数"+ Arrays.toString(args)+",异常对象"+e);
    }

    @After("pointcutName()")
    public void after(){
        System.out.println("after");
    }

    @Around("pointcutName()")
    public Object time(ProceedingJoinPoint jp) throws Throwable {

        Object proxy=jp.getThis();
        Object target=jp.getTarget();
        String methodName=jp.getSignature().getName();
        Object[] args=jp.getArgs();

        System.out.println("proxy = " + proxy.getClass());
        System.out.println("target = " + target.getClass());
        System.out.println("methodName = " + methodName);
        System.out.println("args = " + args);

        long start=0;
        long end=0;
        Object result=null;

        try {
            System.out.println("开始");
            start=System.currentTimeMillis();

            result=jp.proceed();

            end=System.currentTimeMillis();
            System.out.println("结束");
        } catch (Exception e) {
            end=System.currentTimeMillis();
            System.out.println("出错");
            throw e;
        } finally {
            System.out.println(methodName+" "+(end-start));
        }

        return result;
    }

}
